import router from '@/router'
import { useUserStore } from '@/store'

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()

  if (to.path == '/forgotpwd') {
    next()
  } else if (to.path == '/register') {
    next()
  } else if (to.path == '/no-content') {
    next()
  } else if (localStorage.getItem('token')) {
    // 如果即将跳转的页面是登录页，则直接跳转
    if (to.path === '/login') {
      next()
      return
    }
    try {
      next()
      // 获取用户信息
      await userStore.getUserInfo()
    } catch (error) {
      next('/login') // 获取用户信息失败时跳转到登录页面
    }
  } else if (to.path !== '/login') {
    next('/login') // 用户未登录时跳转到登录页面
  } else {
    next()
  }
})

// 每次路由切换之后，判断是否跳转到了登录页面，如果是，则调用userStore.logout()方法执行用户注销操作
router.afterEach(to => {
  if (to.path === '/login') {
    const userStore = useUserStore()
    userStore.logout()
  }
})
